#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 305;
const int INF = 10000;
struct st {
  int x, y, t;
};
int dx[] = {-1, 0, 1, 0, 0};
int dy[] = {0, 1, 0, -1, 0};
int m[maxn][maxn];
bool vis[maxn][maxn];
int M;
int bfs() {
  if(m[0][0]==0) return -1;
  vis[0][0] = true;
  queue<st> q;
  {st tmp={0,0,0}; q.push(tmp);}
  while(q.size()) {
    int x=q.front().x, y=q.front().y, t=q.front().t; q.pop();
    if(m[x][y] == INF) return t;
    for(int i=0; i<4; ++i) {
      int nx = x+dx[i], ny = y+dy[i];
      if(nx<0 || ny<0 || nx>=maxn || ny>=maxn || vis[nx][ny] || t+1>=m[nx][ny]) continue;
      vis[nx][ny] = true;
      st tmp = {nx, ny, t+1};
      q.push(tmp);
    }
  }
  return -1;
}
int main() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  for(int i=0; i<maxn; ++i)
    for(int j=0; j<maxn; ++j)
      m[i][j] = INF;
  cin>>M;
  for(int i=0; i<M; ++i) {
    int x, y, t; cin>>x>>y>>t;
    for(int j=0; j<5; ++j) {
      int nx = x+dx[j], ny=y+dy[j];
      if(nx<0||ny<0) continue;
      m[nx][ny] = min(m[nx][ny], t);
    }
  }
  cout<<bfs()<<'\n';
}
